from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse

from common.models import User, Area, House
from user_app.forms import UserRegisterForm, UserLoginForm
from user_app.models import Order


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    if request.method == 'POST':

        form = UserRegisterForm(request.POST, request.FILES)
        if form.is_valid():
            User.objects.create(phone=form.cleaned_data.get('mobile'),
                                secret_pwd=form.cleaned_data.get('password'))
            return HttpResponseRedirect(reverse('user:login'))

        errors = form.errors
        return render(request, 'register.html', {'errors': errors})


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    if request.method == 'POST':
        form = UserLoginForm(request.POST, request.FILES)
        if form.is_valid():
            request.session['user_id'] = form.cleaned_data['user'].id
            request.user = form.cleaned_data['user']
            return HttpResponseRedirect(reverse('user:index'))
        errors = form.errors
        return render(request, 'login.html', {'errors': errors})


def logout(request):
    if request.method == 'GET':
        # request.session.flush()
        # session_key = request.session.session_key
        del request.session['user_id']
        # request.session.delete(session_key)
        return HttpResponseRedirect(reverse('user:index'))


def my(request):
    if request.method == 'GET':

        return render(request, 'my.html')


def index(request):
    if request.method == 'GET':
        houses = House.objects.all()
        if 'user_id' in request.session:
            # 过滤自己的房源
            houses = House.objects.filter(~Q(user_h=request.user)).all()
        # 过滤订单处于处理状态的house
        orders = Order.objects.filter(~Q(status__in=["REJECTED", "CANCELED"])).all()
        for order in orders:
            houses = houses.filter(~Q(pk=order.house_order.id)).all()
        areas = Area.objects.all()
        return render(request, 'index.html', {'areas': areas, 'houses': houses})


